package cn.cyh.queue_service.controller;

import cn.cyh.queue_service.common.Result;
import cn.cyh.queue_service.config.security.JwtTokenProvider;
import cn.cyh.queue_service.model.dto.LoginRequest;
import cn.cyh.queue_service.model.dto.LoginResponse;
import cn.cyh.queue_service.model.dto.RegisterRequest;
import cn.cyh.queue_service.model.vo.UserVO;
import cn.cyh.queue_service.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

/**
 * 认证接口控制器
 */
@RestController
@RequestMapping("/auth")
@Tag(name = "用户认证", description = "用户认证相关接口")
@Slf4j
@RequiredArgsConstructor
public class AuthController {

    private final UserService userService;
    private final JwtTokenProvider jwtTokenProvider;
    
    @Value("${jwt.header}")
    private String jwtHeader;
    
    @Value("${jwt.token-prefix}")
    private String jwtTokenPrefix;
    
    /**
     * 用户登录
     *
     * @param loginRequest 登录请求
     * @return 登录响应
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "用户登录接口，返回JWT令牌")
    public Result<LoginResponse> login(@Valid @RequestBody LoginRequest loginRequest) {
        log.info("用户登录请求: {}", loginRequest.getUsername());
        LoginResponse response = userService.login(loginRequest);
        return Result.success(response);
    }
    
    /**
     * 用户注册
     *
     * @param registerRequest 注册请求
     * @return 注册结果
     */
    @PostMapping("/register")
    @Operation(summary = "用户注册", description = "用户注册接口，返回注册结果")
    public Result<Long> register(@Valid @RequestBody RegisterRequest registerRequest) {
        log.info("用户注册请求: {}", registerRequest.getUsername());
        Long userId = userService.register(registerRequest);
        return Result.success(userId);
    }
    
    /**
     * 获取当前用户信息
     *
     * @return 当前用户信息
     */
    @GetMapping("/current-user")
    @Operation(summary = "获取当前用户信息", description = "获取当前登录用户的信息")
    public Result<UserVO> getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        log.info("获取当前用户信息: {}", username);
        UserVO userVO = userService.getUserById(userService.getByUsername(username).getId());
        return Result.success(userVO);
    }
    
    /**
     * 刷新令牌
     *
     * @param request HTTP请求
     * @return 新的令牌
     */
    @PostMapping("/refresh-token")
    @Operation(summary = "刷新令牌", description = "使用当前有效的JWT令牌获取新的令牌")
    public Result<LoginResponse> refreshToken(HttpServletRequest request) {
        String bearerToken = request.getHeader(jwtHeader);
        if (bearerToken != null && bearerToken.startsWith(jwtTokenPrefix + " ")) {
            String token = bearerToken.substring(jwtTokenPrefix.length() + 1);
            if (jwtTokenProvider.validateToken(token)) {
                Authentication authentication = jwtTokenProvider.getAuthentication(token);
                String username = authentication.getName();
                log.info("刷新令牌: {}", username);
                
                // 生成新令牌
                String newToken = jwtTokenProvider.generateToken(authentication);
                
                // 获取用户信息
                UserVO userVO = userService.getUserById(userService.getByUsername(username).getId());
                
                // 构建响应
                LoginResponse response = LoginResponse.builder()
                        .userId(userVO.getId())
                        .username(userVO.getUsername())
                        .name(userVO.getName())
                        .role(userVO.getRole())
                        .avatar(userVO.getAvatar())
                        .token(newToken)
                        .tokenType(jwtTokenPrefix)
                        .expiresIn(jwtTokenProvider.getExpirationTime())
                        .build();
                
                return Result.success(response);
            }
        }
        
        return Result.unauthorized("无效的令牌");
    }
    
    /**
     * 用户注销
     *
     * @return 注销结果
     */
    @PostMapping("/logout")
    @Operation(summary = "用户注销", description = "用户注销接口")
    public Result<Void> logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            String username = authentication.getName();
            log.info("用户注销: {}", username);
            // 清除身份验证
            SecurityContextHolder.clearContext();
        }
        return Result.success();
    }
    
    /**
     * 检查用户名是否可用
     *
     * @param username 用户名
     * @return 用户名是否可用
     */
    @GetMapping("/check-username")
    @Operation(summary = "检查用户名是否可用", description = "检查用户名是否已被注册")
    public Result<Boolean> checkUsername(@Parameter(description = "用户名") @RequestParam String username) {
        log.info("检查用户名是否可用: {}", username);
        boolean exists = userService.getByUsername(username) != null;
        return Result.success(!exists);
    }
} 